const fs = require('fs');
const path = require('path');
const multiparty = require('multiparty');
const { uploadPath } = require('../serverOpt');
const axios = require('axios');

class FileUploader {
    constructor() {
        // 确保上传目录存在
        if (!fs.existsSync(uploadPath)) {
            fs.mkdirSync(uploadPath, { recursive: true });
        }
        // 创建临时文件夹
        this.chunksPath = path.join(uploadPath, 'chunks');
        if (!fs.existsSync(this.chunksPath)) {
            fs.mkdirSync(this.chunksPath, { recursive: true });
        }
    }

    // 处理多文件分片上传
    async handleMultipleFilesUpload(req) {
        return new Promise((resolve, reject) => {
            const form = new multiparty.Form();

            form.parse(req, async (err, fields, files) => {
                if (err) {
                    return reject(err);
                }
                try {
                    // 获取所有文件分片信息
                    const fileIdentifiers = fields.fileIdentifiers ? JSON.parse(fields.fileIdentifiers[0]) : [];
                    const results = [];

                    // 处理每个文件的分片
                    for (let i = 0; i < files.files.length; i++) {
                        const chunk = files.files[i];
                        const fileInfo = fileIdentifiers[i];
                        const { chunkNumber, totalChunks, fileName, identifier } = fileInfo;

                        // 创建文件专属的临时目录
                        const fileChunkDir = path.join(this.chunksPath, identifier);
                        if (!fs.existsSync(fileChunkDir)) {
                            fs.mkdirSync(fileChunkDir, { recursive: true });
                        }

                        // 移动分片到临时目录
                        const chunkPath = path.join(fileChunkDir, `chunk-${chunkNumber}`);
                        // await fs.promises.rename(chunk.path, chunkPath);
                        await fs.promises.copyFile(chunk.path, chunkPath); // 复制文件
                        await fs.promises.unlink(chunk.path); // 删除源文件

                        // 检查是否所有分片都已上传
                        const uploadedChunks = fs.readdirSync(fileChunkDir);
                        const isComplete = uploadedChunks.length === parseInt(totalChunks);

                        if (isComplete) {
                            // 合并文件
                            const finalFileName = `${Date.now()}-${fileName}`;
                            const finalPath = path.join(uploadPath, finalFileName);
                            await this.mergeChunks(fileChunkDir, finalPath, totalChunks);

                            // 清理临时文件
                            fs.rmSync(fileChunkDir, { recursive: true });

                            // 获取文件信息
                            const stats = fs.statSync(finalPath);
                            results.push({
                                expire_time:fields.expire_time[0],
                                fileName,
                                fileUrl: `/uploads/${finalFileName}`,
                                size: stats.size,
                                completed: true,
                                identifier
                            });
                        } else {
                            results.push({
                                chunkNumber,
                                uploaded: uploadedChunks.length,
                                total: totalChunks,
                                completed: false,
                                identifier
                            });
                        }
                    }

                    resolve(results);
                } catch (error) {
                    console.trace(error)
                    reject(error);
                }
            });
        });
    }

    // 检查文件上传状态
    checkChunkStatus(identifier) {
        const fileChunkDir = path.join(this.chunksPath, identifier);
        if (fs.existsSync(fileChunkDir)) {
            const uploadedChunks = fs.readdirSync(fileChunkDir);
            return {
                uploaded: uploadedChunks.length,
                uploadedChunks: uploadedChunks.map(chunk => 
                    parseInt(chunk.split('-')[1])
                )
            };
        }
        return {
            uploaded: 0,
            uploadedChunks: []
        };
    }

    // 合并文件分片
    async mergeChunks(chunksDir, destPath, totalChunks) {
        const writeStream = fs.createWriteStream(destPath);
        
        for (let i = 1; i <= totalChunks; i++) {
            const chunkPath = path.join(chunksDir, `chunk-${i}`);
            const chunkData = await fs.promises.readFile(chunkPath);
            await new Promise((resolve, reject) => {
                writeStream.write(chunkData, error => {
                    if (error) reject(error);
                    else resolve();
                });
            });
        }

        return new Promise((resolve, reject) => {
            writeStream.end(err => {
                if (err) reject(err);
                else resolve();
            });
        });
    }
}



module.exports = new FileUploader();
